<?php
/**
 * Author: Hancock
 * Email: 84622365@qq.com
 * Date: 7/18/2016
 * Des: 系统管理员
 */
defined('INHkMvc') or exit('Access Invalid!');

class App_member_orderModel extends AppModel
{
    public function getOrderInfoByExcel($file_path, $page = 0, $is_spread)
    {
        $dataset = read_excel($file_path, $page);
        if ($dataset === false) {
            return false;
        } else {
            $count = count($dataset);
            $j = 0;
            $data = [];
            for ($i = 30; $i <= $count - 30; $i++) {
                if ($i % 30 == 0) {
                    $data[$j]['add_time'] = strtotime($dataset[$i]);
                    $data[$j]['title'] = $dataset[$i + 2];
                    $data[$j]['num_iid'] = $dataset[$i + 3];
                    $data[$j]['seller_id'] = $dataset[$i + 4];
                    $data[$j]['seller_shop'] = $dataset[$i + 5];
                    $data[$j]['good_num'] = $dataset[$i + 6];
                    $data[$j]['good_price'] = $dataset[$i + 7];
                    $data[$j]['status'] = $dataset[$i + 8];
                    $data[$j]['order_status'] = $this->changeOrderStatus($dataset[$i + 8]);
                    $shop_rate = M('app.admin_seller')->getGoodTkRateBySellerId($data[$j]['num_iid']);
                    $define_tk_rate = M('app.good')->getGoodDefineTkRateBySellerId($data[$j]['num_iid']);
                    $data[$j]['shop_rate'] = $shop_rate;
                    $data[$j]['tb_tk_rate'] = $data[$j]['tk_rate'] = $dataset[$i + 10];
                    $tk_rate = M('app.good')->getGoodTkRateByNumId($data[$j]['num_iid']);
                    if ($tk_rate === false) {
                        $data[$j]['tk_rate'] = $dataset[$i + 10] * $dataset[$i + 11] / 100;
                        $data[$j]['good_tk_rate'] = $dataset[$i + 10];
                    } else {
                        $data[$j]['tk_rate'] = min((float)$data[$j]['tk_rate'], $tk_rate) * $dataset[$i + 11] / 100;
                        $data[$j]['good_tk_rate'] = $tk_rate;
                    }
                    $data[$j]['divide_rate'] = $dataset[$i + 11];
                    $data[$j]['pay_money'] = $dataset[$i + 12];
                    $data[$j]['tb_effect_est_income'] = $dataset[$i + 13];
                    $data[$j]['est_effect_income'] = round($data[$j]['pay_money'] * $data[$j]['tk_rate'] / 100, 2);
                    $data[$j]['balance_money'] = $dataset[$i + 14];
                    $data[$j]['tb_est_income'] = $dataset[$i + 15];
                    if (intval($data[$j]['balance_money']) == 0 || $data[$j]['balance_money'] == NULL) {
                        $data[$j]['est_income'] = round($data[$j]['pay_money'] * $data[$j]['tk_rate'] / 100, 2);
                    } else {
                        $data[$j]['est_income'] = round($data[$j]['balance_money'] * $data[$j]['tk_rate'] / 100, 2);
                    }
                    $rate = 0;
                    $rate_time = time();
                    if ($define_tk_rate > 0) {
                        $rate = $define_tk_rate;
                        $rate_time = M('app.good')->getGoodRateTimeBySellerId($data[$j]['num_iid']);
                    } else if ($shop_rate > 0) {
                        $rate = $shop_rate;
                        $rate_time = M('app.admin_seller')->getGoodRateTimeBySellerId($data[$j]['num_iid']);
                    } else {
                        $rate_time = time();
                    }
                    if ($rate_time > $data[$j]['add_time']) {
                        $rate = 0;
                    }
                    if ($rate > 0) {
                        $data[$j]['est_effect_income'] = round($data[$j]['pay_money'] * $rate / 100, 2);
                        if (intval($data[$j]['balance_money']) == 0 || $data[$j]['balance_money'] == NULL) {
                            $data[$j]['est_income'] = round($data[$j]['pay_money'] * $rate / 100, 2);
                        } else {
                            $data[$j]['est_income'] = round($data[$j]['balance_money'] * $rate / 100, 2);
                        }
                    } else {
                        $data[$j]['shop_rate'] = 0;
                        $data[$j]['define_tk_rate'] = 0;
                    }
                    $cutoff_time = $data[$j]['cutoff_time'] = intval(strtotime($dataset[$i + 16]));
                    $time = $this->getTimeCondition();
                    if ($cutoff_time > 0 && $cutoff_time < $time) {
                        $data[$j]['order_status'] = 2;
                    }
                    $data[$j]['commision_rate'] = $dataset[$i + 17];
                    $data[$j]['commision_money'] = $dataset[$i + 18];
                    $data[$j]['allowance_rate'] = $dataset[$i + 19];
                    $data[$j]['allowance_money'] = $dataset[$i + 20];
                    $data[$j]['order_number'] = $dataset[$i + 24];
                    $ad_zone_id = $data[$j]['ad_zone_id'] = $dataset[$i + 28];
                    $data[$j]['ad_name'] = $dataset[$i + 29];
                    $data[$j]['level'] = M('app.member_vip')->getMemberVipLevelByAdZoneId($ad_zone_id)['level'];
                    $data[$j]['is_true'] = 1;
                    $data[$j]['is_spread'] = $is_spread;
                    $j++;
                }
            }
            return $data;
        }
    }

    public function addExcelInfo($file_path, $page, $time, $is_spread, $site_name = "dekahome")
    {
        $this->begin();
        $data = $this->getOrderInfoByExcel($file_path, $page, $is_spread);
        if (count($data) == 0) {
            return true;
        }
        if ($data == false) {
            return false;
        } else {
            $number = count($data);
            $Excel_time = strtotime(date('Y-m-d', $data[0]['add_time']));
            $time_msg = $this->confirmTimeByExcel($data, $time, $Excel_time);
            if ($time_msg === false) {
                $this->rollback();
                return false;
            }
            $where['add_time'] = array('between', array($time, $time + 86400 - 1));
            $where['is_edit'] = 0;
            $where['is_spread'] = $is_spread;
            $where['site_name'] = $site_name;
            $res = $this->select($where);
            if (date('Y-m-d', $time) == date('Y-m-d', $Excel_time)) {
                if (isset($res) && $res != NULL) {
                    if (count($res) != $number) {
                        $res = $this->delete($where);
                        if ($res === false) {
                            $this->rollback();
                            return false;
                        }
                        $member_order = $this->insertMemberOrderExcel($data, $number, $is_spread, $site_name);
                        if ($member_order === false) {
                            $this->rollback();
                            return false;
                        }
                    } else {
                        $member_order = $this->updateMemberOrderExcel($data, $number, $is_spread);
                        if ($member_order === false) {
                            $this->rollback();
                            return false;
                        }
                    }
                } else {
                    $member_order = $this->insertMemberOrderExcel($data, $number, $is_spread, $site_name);
                    if ($member_order === false) {
                        $this->rollback();
                        return false;
                    }
                }
            } else {
                $this->rollback();
                return false;
            }
            $this->commit();
            return true;
        }
    }

    public function insertMemberOrderExcel($data, $number, $is_spread, $site_name = "dekahome")
    {
        for ($i = 0; $i <= $number - 1; $i++) {
            $datas = $data[$i];
            $datas['sort'] = $i;
            $datas['site_name'] = $site_name;
            $res = $this->insert($datas);
            if ($res === false) {
                return false;
            }
            $member_id = $this->updateMemberId($datas['ad_zone_id']);
            $update_member = @$this->update(['member_id' => $member_id['member_id']], ['id' => $res]);
            if ($update_member === false) {
                return false;
            }
            $order = M('app.order')->editOrderList($datas, $member_id['member_id']);
            if ($order === false) {
                return false;
            }
            if ($datas['order_status'] != 0) {
                $order_time = M('app.member_vip')->editOrderTime($datas['add_time'], $member_id['member_id']);
            }
            if (intval($datas['level']) >= 1) {
                $member_vip_money = @$this->getMoneyNum($member_id['member_id'], $datas['level']);
                if ($member_vip_money === false) {
                    return false;
                }
                $money = M('app.member_vip')->field('total,used,freeze,est_income')->find(['member_id' => $member_id['member_id'], 'status' => 1]);
                if ($money['total'] != $member_vip_money[0] || $money['est_income'] != $member_vip_money[1]) {
                    $update_money = M('app.member_vip')->update(['total' => $member_vip_money[0], 'update_time' => time(), 'est_income' => $member_vip_money[1], 'unbalance' => $member_vip_money[1] - $member_vip_money[0], 'balance' => $member_vip_money[0] - $money['used'] - $money['freeze']], ['member_id' => $member_id['member_id'], 'status' => 1]);
                    if ($update_money === false) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public function updateMemberOrderExcel($data, $number, $is_spread)
    {
        for ($i = 0; $i <= $number - 1; $i++) {
            $order_number = $data[$i]['order_number'];
            $where = array('order_number' => $order_number, 'sort' => $i, 'is_edit' => 0);
            $result = $this->field('id,member_id,order_status,level,tk_rate,tb_tk_rate,good_tk_rate,shop_rate,define_tk_rate')->find($where);
            $member_id = $this->updateMemberId($data[$i]['ad_zone_id']);
            if ($member_id != 0) {
                $result['member_id'] = $member_id['member_id'];
                $data[$i]['member_id'] = $member_id['member_id'];
            }
            if (isset($result) && $result != NULL) {
                $datas = $data[$i];
                if (intval($result['good_tk_rate']) != 0) {
                    $datas['good_tk_rate'] = $result['good_tk_rate'];
                } else {
                    $result['good_tk_rate'] = $datas['good_tk_rate'];
                }
                if (intval($result['level']) > 0) {
                    $datas['level'] = intval($result['level']);
                }
                if ($result['tk_rate'] != trim($datas['tk_rate'], '%')) {
                    if ($result['tb_tk_rate'] > trim($datas['tb_tk_rate'], '%')) {
                        $datas['tk_rate'] = min($datas['tb_tk_rate'], $result['good_tk_rate']) * $datas['divide_rate'] / 100;
                    } else {
                        if (intval($result['tb_tk_rate']) > 0) {
                            $datas['tk_rate'] = min($result['tb_tk_rate'], $result['good_tk_rate']) * $datas['divide_rate'] / 100;
                            $datas['tb_tk_rate'] = $result['tb_tk_rate'];
                        } else {
                            $datas['tk_rate'] = min($datas['tb_tk_rate'], $result['good_tk_rate']) * $datas['divide_rate'] / 100;
                        }
                    }
                    $datas['est_effect_income'] = round($datas['pay_money'] * $datas['tk_rate'] / 100, 2);
                    if (intval($datas['balance_money']) == 0 || $datas['balance_money'] == NULL) {
                        $datas['est_income'] = round($datas['pay_money'] * $datas['tk_rate'] / 100, 2);
                    } else {
                        $datas['est_income'] = round($datas['balance_money'] * $datas['tk_rate'] / 100, 2);
                    }
                }
                if ($result['define_tk_rate'] > 0) {
                    $datas['define_tk_rate'] = $result['define_tk_rate'];
                    $datas['est_effect_income'] = round($datas['pay_money'] * $result['define_tk_rate'] / 100, 2);
                    if (intval($datas['balance_money']) == 0 || $datas['balance_money'] == NULL) {
                        $datas['est_income'] = round($datas['pay_money'] * $result['define_tk_rate'] / 100, 2);
                    } else {
                        $datas['est_income'] = round($datas['balance_money'] * $result['define_tk_rate'] / 100, 2);
                    }
                } else if ($result['shop_rate'] > 0) {
                    $datas['shop_rate'] = $result['shop_rate'];
                    $datas['est_effect_income'] = round($datas['pay_money'] * $result['shop_rate'] / 100, 2);
                    if (intval($datas['balance_money']) == 0 || $datas['balance_money'] == NULL) {
                        $datas['est_income'] = round($datas['pay_money'] * $result['shop_rate'] / 100, 2);
                    } else {
                        $datas['est_income'] = round($datas['balance_money'] * $result['shop_rate'] / 100, 2);
                    }
                } else {
                    $datas['define_tk_rate'] = 0;
                    $datas['shop_rate'] = 0;
                }
                $datas['update_time'] = time();
                $res = @$this->update($datas, ['id' => $result['id']]);
                if ($res === false) {
                    return false;
                }
                $order = M('app.order')->editOrderList($datas, $member_id['member_id']);
                if ($order === false) {
                    return false;
                }
                if ($datas['order_status'] != 0) {
                    $order_time = M('app.member_vip')->editOrderTime($datas['add_time'], $member_id['member_id']);
                }
                if (intval($datas['level']) >= 1) {
                    $member_vip_money = @$this->getMoneyNum($result['member_id'], $datas['level']);
                    if ($member_vip_money === false) {
                        return false;
                    }
                    $money = M('app.member_vip')->field('total,used,freeze,est_income')->find(['member_id' => $result['member_id'], 'status' => 1]);
                    if ($money['total'] != $member_vip_money[0] || $money['est_income'] != $member_vip_money[1]) {
                        $update_money = M('app.member_vip')->update(['total' => $member_vip_money[0], 'update_time' => time(), 'est_income' => $member_vip_money[1], 'unbalance' => $member_vip_money[1] - $member_vip_money[0], 'balance' => $member_vip_money[0] - $money['used'] - $money['freeze']], ['member_id' => $result['member_id'], 'status' => 1]);
                        if ($update_money === false) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    public function changeOrderStatus($order_status)
    {
        if ($order_status == '订单结算' || $order_status == '订单付款') {
            $order_status = 1;
        } else if ($order_status == '订单失效') {
            $order_status = 0;
        }
        return $order_status;
    }

    public function getMoneyNum($member_id, $level)
    {
        $level = M('app.member_vip_level')->getMemberVipLevel($level);
        if ($level === false) {
            return false;
        }
        $last_time = '1451577600';
        $time = $this->getTimeCondition();
        $total_money = $this->countSums('est_income', $member_id, $last_time, $time);
        $commision_money = $this->countSum('est_income', $member_id);
        if ($member_id != 2) {
            $total_money = round($total_money * $level['vip_tk_rate'] * $level['fee'], 2);
            $commision_money = round($commision_money * $level['vip_tk_rate'] * $level['fee'], 2);
        } else {
            $total_money = $total_money;
            $commision_money = $commision_money;
        }
        $balance_money = array($total_money, $commision_money);
        return $balance_money;
    }

    public function countSum($fields, $member_id)
    {
        $commision_money = 0;
        $data = $this->field('est_income')->select(['member_id' => $member_id, 'order_status' => ['<>', 0]]);
        foreach ($data as $k => $v) {
            $commision_money = $v['est_income'] + $commision_money;
        }
        return $commision_money;
    }
    public function countSums($fields, $member_id, $last_time, $time)
    {
        $total_money = 0;
        $data = $this->field('est_income')->select(['member_id' => $member_id, 'order_status' => ['<>', 0], 'cutoff_time' => ['between', [$last_time, $time]]]);
        foreach ($data as $k => $v) {
            $total_money = $v['est_income'] + $total_money;
        }
        return $total_money;
    }

    public function getTimeCondition()
    {
        $time = date('Y-m-d', time());
        $time_arr = explode('-', $time);
        $year = $time_arr[0];
        $month = $time_arr[1];
        $day = $time_arr[2];
        if ($month == 1) {
            if ($day <= 20) {
                $day = 1;
                $month = 12;
                $year = $year - 1;
                $time = strtotime($year . '-' . $month . '-' . $day);
                $time = $time - 1;
                return $time;
            } else {
                $day = 1;
                $time = strtotime($year . '-' . $month . '-' . $day);
                $time = $time - 1;
                return $time;
            }
        } else {
            if ($day <= 20) {
                $day = 1;
                $month = $month - 1;
                $time = strtotime($year . '-' . $month . '-' . $day);
                $time = $time - 1;
                return $time;
            } else {
                $day = 1;
                $time = strtotime($year . '-' . $month . '-' . $day);
                $time = $time - 1;
                return $time;
            }
        }
    }

    public function confirmTimeByExcel($data, $time, $Excel_time)
    {
        if (date('Y-m-d', $time) == date('Y-m-d', $Excel_time)) {
            foreach ($data as $k => $v) {
                $add_time = date('Y-m-d', strtotime(date('Y-m-d', $v['add_time'])));
                if ($add_time != date('Y-m-d', $time) || $add_time != date('Y-m-d', $Excel_time)) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public function updateMemberId($ad_zone_id)
    {
        $member_id = M('app.ad_zone')->field('member_id')->find(['ad_zone_id' => $ad_zone_id])['member_id'];
        $data = [];
        $data['member_id'] = $member_id;
        return $data;
    }
    public function getMemberIntegrationByAddTime($member_id,$order_status=0,$start_time='',$end_time){
        $where=[];
        $where['member_id']=$member_id;
        $where['is_true']=1;
        if($order_status==0){
           $where[]=['order_status'=>['<>',0]];
        }else{
           $where[]=['order_status'=>$order_status];
        }
        if(!empty($start_time)){
           $where[]=['add_time'=>['>=',$start_time]];
        }
        if(!empty($end_time)){
           $where[]=['add_time'=>['<',$end_time]]; 
        }else{
           $where[]=['add_time'=>['<',time()]]; 
        }
        $data=$this->field('est_income')->select($where);
        $money=0;
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $money+=$v['est_income'];
            }
        }
        return $money;
    }
    public function getMemberOrderListByTime($member_id,$start_time,$end_time,$status,$fee)
    {   
        $where=[];
        if ($status!=4) {
            $where = ['member_id' => $member_id,
                'order_status' => $status];
        } else {
            $where = ['member_id' => $member_id];
        }
        $where[]=['add_time'=>['>=',$start_time]];
        $where[]=['add_time'=>['<',$end_time]];
        $join = [
            $this->table => ['left',
                ['num_iid', 'good', 'good.num_iid']
            ]
        ];
        $data=$this->table()->join($join)->field('id,balance_money,pay_money,order_status,status,good.pict_url,good.define_pict_url,good.tk_rate,tk_rate rate,seller_shop,est_effect_income,est_income,good_price,add_time,cutoff_time,order_number,good.define_title define_title,title')->order('add_time desc')->select($where);
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $data[$k]['order_money']=$v['balance_money']?$v['balance_money']:$v['pay_money'];
                $data[$k]['title']=$v['define_title']?$v['define_title']:$v['title'];
                $data[$k]['est_income']=$v['est_income']?$v['est_income']*$fee:$v['est_effect_income']*$fee;
                $data[$k]['rate']=$v['rate']?$v['rate']:$v['tk_rate'];
                $data[$k]['pict_url']=$v['define_pict_url']?$v['define_pict_url']:$v['pict_url'];
            }
        }
        return $data;
    }
    public function getMemberOrderList($member_id, $page = 1, $page_size = 10, $order_status = '')
    {   
        $where=[];
        if (isset($order_status) && $order_status != NULL) {
            $where = ['member_id' => $member_id,
                'order_status' => $order_status];
        } else {
            $where = ['member_id' => $member_id];
        }
        $join = [
            $this->table => ['left',
                ['num_iid', 'good', 'good.num_iid'], ['level', 'member_vip_level', 'member_vip_level.level']
            ]
        ];
        $data=$this->table()->join($join)->field('id,balance_money,pay_money,order_status,good.pict_url,good.tk_rate,tk_rate rate,seller_shop,est_effect_income,est_income,good_price,add_time,cutoff_time,order_number,good.define_title define_title,title,member_vip_level.vip_tk_rate,member_vip_level.fee')->limit(abs($page - 1) * $page_size, $page_size)->order('add_time desc')->select($where);
        if(!empty($data)){
            foreach ($data as $k => $v) {
                if ($v['define_tk_rate']>0) {
                    $data[$k]['rate'] = $v['define_tk_rate'];
                }else if($v['shop_rate']>0){
                    $data[$k]['rate'] = $v['shop_rate'];
                }
                $data[$k]['order_money']=$v['balance_money']?$v['balance_money']:$v['pay_money'];
                $data[$k]['title']=$v['define_title']?$v['define_title']:$v['title'];
                $data[$k]['est_income']=$v['est_income']?$v['est_income']*$fee:$v['est_effect_income']*$fee;
                $data[$k]['rate']=$v['rate']?$v['rate']:$v['tk_rate'];
                $data[$k]['pict_url']=$v['define_pict_url']?$v['define_pict_url']:$v['pict_url'];
            }
        }
        return $data;
    }
    public function getMemberOrderCountByTime($member_id,$start_time,$end_time)
    {   
        $where=[];
        $where[] = ['member_id' => $member_id];
        $where[]=['add_time'=>['>=',$start_time]];
        $where[]=['add_time'=>['<',$end_time]];
        return $this->select($where);
    }
}
